package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.CustomException;
import com.example.common.Result;
import com.example.dto.PositionDto;
import com.example.entity.*;
import com.example.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = {"职位接口列表"})
@RestController
@RequestMapping("/position")
@Slf4j
public class PositionController {


    @Autowired
    private PositionService positionService;

    @Autowired
    private DPService dpService;


    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserAService uaService;


    /**
     * 分页查询，其中部分数据从 departmentPosition表（以下简称dp表或dp）中获得
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation("职位查询")
    @GetMapping("/list")
    public Result<?> list(int page, int pageSize, String name) {

        Page<Position> positionPage = new Page(page, pageSize);
        Page<PositionDto> positionDtoPage = new Page(page, pageSize);

        LambdaQueryWrapper<Position> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        positionLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Position::getName, name);
        positionService.page(positionPage, positionLambdaQueryWrapper);

        List<Position> positionPageRecords = positionPage.getRecords();

        List<PositionDto> collect = positionPageRecords.stream().map(item -> {

            PositionDto positionDto = new PositionDto();
            BeanUtils.copyProperties(item, positionDto);

            LambdaQueryWrapper<DepartmentPosition> departmentPositionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            departmentPositionLambdaQueryWrapper.eq(DepartmentPosition::getPositionId, item.getId());
            DepartmentPosition one = dpService.getOne(departmentPositionLambdaQueryWrapper);

            positionDto.setDepartmentId(one.getDepartmentId());

            LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            departmentLambdaQueryWrapper.eq(Department::getId, one.getDepartmentId());

            positionDto.setDepartmentName(departmentService.getOne(departmentLambdaQueryWrapper).getName());

            return positionDto;

        }).collect(Collectors.toList());

        positionDtoPage.setRecords(collect);


        Map<String, Object> map = new HashMap<>();
        map.put("total", positionPage.getTotal());
        map.put("rows", positionDtoPage.getRecords());
        return Result.success(map);

    }

    /**
     * 添加新职位，联动dp
     *
     * @param positionDto
     * @return
     */
    @ApiOperation("添加职位")
    @PostMapping
    public Result<?> addPosition(@RequestBody PositionDto positionDto) {
        log.info("{}", positionDto);
        long orderId = IdWorker.getId();
        positionDto.setId(orderId);

        positionService.saveWithDP(positionDto);
        return Result.success("新增职位成功");
    }

    /**
     * 修改职位
     * 联动dp
     *
     * @param positionDto
     * @return
     */
    @ApiOperation("修改职位")
    @PutMapping
    public Result<?> updatePosition(@RequestBody PositionDto positionDto) {

        LambdaQueryWrapper<Position> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        positionLambdaQueryWrapper.eq(Position::getId,positionDto.getId());
        Position one = positionService.getOne(positionLambdaQueryWrapper);

        if(one.getStatus() != positionDto.getStatus() && one.getStatus()==1){
            LambdaQueryWrapper<UserA> userALambdaQueryWrapper = new LambdaQueryWrapper<>();
            userALambdaQueryWrapper.eq(UserA::getPositionId,positionDto.getId());
            long count = uaService.count(userALambdaQueryWrapper);
            if (count > 0) {
                return Result.fail("该职位正在使用，不能修改其状态");
            }
        }

        positionService.updateByIdWithDP(positionDto);
        return Result.success("修改职位成功");
    }

    /**
     * 返回职位信息到修改界面，和dp联动
     *
     * @param id
     * @return
     */
    @ApiOperation("返回到修改界面的查询职位")
    @GetMapping("/{id}")
    public Result<PositionDto> getById(@PathVariable Long id) {
        return Result.success(positionService.getByIdWithDP(id));
    }

    /**
     * 删除职位，联动dp
     *
     * @param id
     * @return
     */

    @ApiOperation("删除职位")
    @DeleteMapping("/{id}")
    public Result<?> deletePosition(@PathVariable Long id) {

        LambdaQueryWrapper<UserA> employeeALambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeALambdaQueryWrapper.eq(UserA::getPositionId, id);
        long count = uaService.count(employeeALambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("该职位已关联其他数据，不能删除");
        } else {
            positionService.removeByIdWithDP(id);
            return Result.success("删除职位成功");
        }
    }

    @ApiOperation("修改界面的职位数据")
    @GetMapping("/name")
    public Result<?> getPositionName(Position position) {
        LambdaQueryWrapper<Position> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        positionLambdaQueryWrapper.eq(position.getStatus() != null, Position::getStatus, position.getStatus());
        List<Position> list = positionService.list(positionLambdaQueryWrapper);

        log.info("{}", list);
        return Result.success(list);
    }
}
